package com.aaa.zs.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@Component
public class IllegalCharFilter extends ZuulFilter {
    @Value("${illegal_char}")
    private String illegal_char;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //具体过滤业务代码
        System.out.println("进入了非法字符过滤器。。。。");
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取请求用户的IP地址
        HttpServletRequest request=currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();

        Enumeration<String> parameterNames = request.getParameterNames();
        String[] splits = illegal_char.split(",");
        while (parameterNames.hasMoreElements()){
            String parameterName= parameterNames.nextElement();
            String parameterValue = request.getParameter(parameterName);
            for (String split : splits) {
                if (parameterValue.contains(split)){
                    currentContext.setSendZuulResponse(false);
                    response.setCharacterEncoding("utf-8");
                    try {
                        response.sendError(HttpStatus.SC_FORBIDDEN,"你的请求中含有非法参数，不允许访问");
                        return null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
